import * as fabricModule from 'fabric';
const fabric = fabricModule.fabric || fabricModule;
import { base64ToBlob, fileToDataURL, convertImageFormat } from './utils/imageUtils';

/**
 * 图像编辑服务
 * 封装Fabric.js编辑器，提供图像编辑功能
 */
class ImageEditorService {
    constructor() {
        this.editor = null;
        this.canvas = null;
        this.canvasElement = null;
        this.callbacks = {
            onReady: null,
            onChange: null,
            onImageAdded: null,
            onExport: null
        };
    }

    /**
     * 初始化编辑器
     * @param {HTMLCanvasElement|string} canvasElement - Canvas元素或其ID
     * @param {Object} options - 编辑器选项
     * @returns {Promise<void>}
     */
    init(canvasElement, options = {}) {
        if (this.canvas) {
            console.log('编辑器已初始化，返回现有实例');
            return Promise.resolve(this.editor);
        }

        return new Promise((resolve, reject) => {
            try {
                // 获取Canvas元素
                if (typeof canvasElement === 'string') {
                    this.canvasElement = document.getElementById(canvasElement);
                    if (!this.canvasElement) {
                        throw new Error(`未找到Canvas元素: ${canvasElement}`);
                    }
                } else {
                    this.canvasElement = canvasElement;
                }

                // 直接创建fabric.Canvas，避免使用EditorCore
                this.canvas = new fabric.Canvas(this.canvasElement, {
                    ...options,
                    preserveObjectStacking: true,
                    controlsAboveOverlay: true,
                    stopContextMenu: true
                });

                // 设置背景色
                if (options.backgroundColor) {
                    this.canvas.backgroundColor = options.backgroundColor;
                    this.canvas.renderAll();
                }

                // 设置画布尺寸
                const canvasWidth = options.width || 800;
                const canvasHeight = options.height || 600;
                this.canvas.setWidth(canvasWidth);
                this.canvas.setHeight(canvasHeight);

                // 简单编辑器对象
                this.editor = {
                    canvas: this.canvas,
                    getPlugin: () => {
                        return {
                            addText: (text, options) => {
                                const textObj = new fabric.Text(text, options);
                                this.canvas.add(textObj);
                                this.canvas.setActiveObject(textObj);
                                this.canvas.renderAll();
                                return textObj;
                            },
                            addImage: (url, options = {}) => {
                                return new Promise((resolve, reject) => {
                                    fabric.Image.fromURL(url, (img) => {
                                        img.set(options);
                                        this.canvas.add(img);
                                        this.canvas.setActiveObject(img);
                                        this.canvas.renderAll();
                                        resolve(img);
                                    }, { crossOrigin: 'anonymous' });
                                });
                            }
                        };
                    },
                    on: (eventName, callback) => {
                        this.canvas.on(eventName, callback);
                    }
                };

                if (this.callbacks.onReady) {
                    this.callbacks.onReady({
                        canvas: this.canvas,
                        editor: this.editor
                    });
                }

                resolve(this.editor);
            } catch (error) {
                console.error('初始化编辑器失败:', error);
                reject(error);
            }
        });
    }

    /**
     * 设置事件监听
     * @private
     */
    _setupEventListeners() {
        if (!this.editor) return;

        // 监听对象修改
        this.editor.on('object:modified', () => {
            if (this.callbacks.onChange) {
                this.callbacks.onChange();
            }
        });

        // 监听对象添加
        this.editor.on('object:added', (obj) => {
            if (this.callbacks.onChange) {
                this.callbacks.onChange();
            }
        });

        // 监听对象删除
        this.editor.on('object:removed', () => {
            if (this.callbacks.onChange) {
                this.callbacks.onChange();
            }
        });

        // 监听图像添加
        this.editor.on('image:added', (img) => {
            if (this.callbacks.onImageAdded) {
                this.callbacks.onImageAdded(img);
            }
        });
    }

    /**
     * 调整编辑器大小
     * @param {number} width - 宽度
     * @param {number} height - 高度
     * @private
     */
    _resizeEditor(width, height) {
        if (!this.editor) return;

        const canvasWidth = width || this.canvasElement.parentElement.clientWidth || 800;
        const canvasHeight = height || this.canvasElement.parentElement.clientHeight || 600;

        this.editor.setWorkspaceSize(canvasWidth, canvasHeight);
    }

    /**
     * 设置回调函数
     * @param {Object} callbacks - 回调函数对象
     */
    setCallbacks(callbacks = {}) {
        this.callbacks = { ...this.callbacks, ...callbacks };
        return this;
    }

    /**
     * 从URL或DataURL加载图像
     * @param {string} url - 图像URL或DataURL
     * @param {Object} options - 选项
     * @returns {Promise<Object>} 添加的图像对象
     */
    loadImage(url, options = {}) {
        if (!this.canvas) {
            return Promise.reject(new Error('编辑器未初始化'));
        }

        return new Promise((resolve, reject) => {
            fabric.Image.fromURL(url, (img) => {
                img.set(options);
                this.canvas.add(img);
                this.canvas.setActiveObject(img);
                this.canvas.renderAll();
                resolve(img);
            }, { crossOrigin: 'anonymous' });
        });
    }

    /**
     * 从文件加载图像
     * @param {File} file - 图像文件
     * @param {Object} options - 选项
     * @returns {Promise<Object>} 添加的图像对象
     */
    async loadImageFromFile(file, options = {}) {
        if (!this.canvas) {
            return Promise.reject(new Error('编辑器未初始化'));
        }

        try {
            const dataUrl = await fileToDataURL(file);
            return this.loadImage(dataUrl, options);
        } catch (error) {
            console.error('加载图像文件失败:', error);
            throw error;
        }
    }

    /**
     * 裁剪当前选中图像
     * @param {Object} cropRect - 裁剪矩形 {left, top, width, height}
     * @returns {Promise<Object>} 裁剪后的图像
     */
    cropSelectedImage(cropRect) {
        if (!this.editor) {
            return Promise.reject(new Error('编辑器未初始化'));
        }

        const activeObject = this.editor.canvas.getActiveObject();
        if (!activeObject || activeObject.type !== 'image') {
            return Promise.reject(new Error('未选中图像'));
        }

        return this.editor.getPlugin('ImagePlugin').cropImage(activeObject, cropRect);
    }

    /**
     * 应用滤镜到当前选中图像
     * @param {string} filterType - 滤镜类型
     * @param {Object} options - 滤镜选项
     * @returns {Object} 应用滤镜后的图像
     */
    applyFilterToSelectedImage(filterType, options = {}) {
        if (!this.editor) {
            throw new Error('编辑器未初始化');
        }

        const activeObject = this.editor.canvas.getActiveObject();
        if (!activeObject || activeObject.type !== 'image') {
            throw new Error('未选中图像');
        }

        return this.editor.getPlugin('ImagePlugin').applyFilter(activeObject, filterType, options);
    }

    /**
     * 调整当前选中图像属性
     * @param {Object} adjustments - 调整参数 {brightness, contrast, saturation, etc}
     * @returns {Object} 调整后的图像
     */
    adjustSelectedImage(adjustments = {}) {
        if (!this.editor) {
            throw new Error('编辑器未初始化');
        }

        const activeObject = this.editor.canvas.getActiveObject();
        if (!activeObject || activeObject.type !== 'image') {
            throw new Error('未选中图像');
        }

        return this.editor.getPlugin('ImagePlugin').adjustImage(activeObject, adjustments);
    }

    /**
     * 旋转当前选中图像
     * @param {number} angle - 旋转角度（度数）
     * @returns {Object} 旋转后的图像
     */
    rotateSelectedImage(angle) {
        if (!this.editor) {
            throw new Error('编辑器未初始化');
        }

        const activeObject = this.editor.canvas.getActiveObject();
        if (!activeObject || activeObject.type !== 'image') {
            throw new Error('未选中图像');
        }

        return this.editor.getPlugin('ImagePlugin').rotateImage(activeObject, angle);
    }

    /**
     * 导出画布为图像
     * @param {Object} options - 导出选项
     * @param {string} options.format - 图像格式 ('png', 'jpeg', 'webp')
     * @param {number} options.quality - 图像质量 (0-1)
     * @param {boolean} options.includeBackground - 是否包含背景
     * @returns {Promise<string>} 图像的DataURL
     */
    exportToImage(options = {}) {
        if (!this.editor) {
            return Promise.reject(new Error('编辑器未初始化'));
        }

        return new Promise((resolve) => {
            const format = options.format || 'png';
            const quality = options.quality || 0.9;
            const includeBackground = options.includeBackground !== false;

            // 获取原始背景
            const originalBg = this.editor.canvas.backgroundColor;

            // 如果不包含背景，临时设置为透明
            if (!includeBackground) {
                this.editor.canvas.backgroundColor = 'rgba(0,0,0,0)';
                this.editor.canvas.renderAll();
            }

            // 导出画布
            const dataURL = this.editor.canvas.toDataURL({
                format: format,
                quality: quality
            });

            // 恢复原始背景
            if (!includeBackground) {
                this.editor.canvas.backgroundColor = originalBg;
                this.editor.canvas.renderAll();
            }

            if (this.callbacks.onExport) {
                this.callbacks.onExport(dataURL);
            }

            resolve(dataURL);
        });
    }

    /**
     * 导出画布为Blob对象
     * @param {Object} options - 导出选项
     * @returns {Promise<Blob>} 图像的Blob对象
     */
    async exportToBlob(options = {}) {
        const dataURL = await this.exportToImage(options);
        return base64ToBlob(dataURL);
    }

    /**
     * 设置背景颜色
     * @param {string} color - 颜色值
     */
    setBackgroundColor(color) {
        if (!this.canvas) {
            throw new Error('编辑器未初始化');
        }

        this.canvas.backgroundColor = color;
        this.canvas.renderAll();
        return this;
    }

    /**
     * 清空画布
     */
    clear() {
        if (!this.editor) return;
        this.editor.canvas.clear();
    }

    /**
     * 撤销操作
     */
    undo() {
        if (!this.editor) return;
        this.editor.undo();
    }

    /**
     * 重做操作
     */
    redo() {
        if (!this.editor) return;
        this.editor.redo();
    }

    /**
     * 销毁编辑器实例
     */
    destroy() {
        if (!this.editor) return;
        this.editor.destroy();
        this.editor = null;
        this.canvasElement = null;
    }
}

// 创建单例实例
export const imageEditorService = new ImageEditorService();

// 默认导出服务实例
export default imageEditorService; 